<?php

require __DIR__.'/../vendor/autoload.php';
// require_once __DIR__.'/../bootstrap/database.php';

// 初始化PDO数据库连接
$dbConfig = require __DIR__.'/../config/database.php';
$connection = $dbConfig['connections'][$dbConfig['default']];

try {
    $port = $connection['port'] ?? ($connection['driver'] == 'mysql' ? 3306 : 5432);
    $pdo = new PDO(
        "{$connection['driver']}:host={$connection['host']};port={$port};dbname={$connection['database']}",
        $connection['username'],
        $connection['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

use App\Services\CollegeLogoDownloadService;

class LogoDownloadScript
{
    protected $downloader;

    public function __construct()
    {
        $this->downloader = new CollegeLogoDownloadService();
    }

    public function run()
    {
        try {
            //$this->validateEnvironment();
            //$this->runDownloadProcess();
            $this->runCollegeClassifyProcess();
        } catch (\Exception $e) {
            $this->handleError($e);
        }
    }

    /**
     * @throws Exception
     */
    protected function validateEnvironment(): void
    {
        global $pdo;

        // 测试数据库连接
        try {
            $pdo->query("SELECT 1");
            echo "✓ Database connection OK\n";
        } catch (PDOException $e) {
            throw new \Exception("Database connection failed: " . $e->getMessage());
        }

        // 验证表是否存在
        try {
            $stmt = $pdo->query("SELECT COUNT(*) FROM information_schema.tables 
                               WHERE table_schema = DATABASE() AND table_name = 'college'");
            $tableExists = $stmt->fetchColumn() > 0;

            if (!$tableExists) {
                throw new \Exception("Table 'college' does not exist");
            }

            // 获取学院数量
            $stmt = $pdo->query("SELECT COUNT(*) FROM college");
            $collegeCount = $stmt->fetchColumn();
            echo "✓ Found {$collegeCount} colleges in database\n";

            // 验证字段存在
            $stmt = $pdo->query("SHOW COLUMNS FROM college");
            $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
            $requiredColumns = ['school_id', 'college_id'];

            foreach ($requiredColumns as $column) {
                if (!in_array($column, $columns)) {
                    throw new \Exception("Required column '{$column}' missing in college table");
                }
            }
        } catch (PDOException $e) {
            throw new \Exception("Database query failed: " . $e->getMessage());
        }
    }

    /**
     * @Notes: 下载院校logo
     * @Interface runDownloadProcess
     * @throws ReflectionException
     * @Time: 2025/6/20   13:45
     */
    protected function runDownloadProcess(): void
    {
        global $pdo;

        echo "\nStarting download process...\n";
        $startTime = microtime(true);

        // 获取所有需要下载的学院
        $stmt = $pdo->query("SELECT school_id, college_id FROM college");
        $colleges = $stmt->fetchAll(PDO::FETCH_OBJ);
        $total = count($colleges);

        // 执行下载并显示进度
        $downloaded = 0;
        $total = count($colleges);

        foreach ($colleges as $college) {
            // 通过反射调用私有方法
            $method = new ReflectionMethod(get_class($this->downloader), 'downloadLogo');
            $method->setAccessible(true);
            $method->invokeArgs($this->downloader, [
                $college->school_id,
                $college->college_id
            ]);
            $downloaded++;
            echo "Progress: {$downloaded}/{$total}\r";
            $this->logMemoryUsage();
        }

        $endTime = microtime(true);
        $executionTime = round($endTime - $startTime, 2);

        echo "\n✓ Successfully completed in {$executionTime} seconds.\n";
        error_log("Logo download completed in {$executionTime} seconds");
    }

    protected function runCollegeClassifyProcess()
    {
        global $pdo;

        echo "\nStarting download process...\n";
        $startTime = microtime(true);

        // 获取所有需要下载的学院
        $stmt = $pdo->query("SELECT yikao_college.school_id, f211, f985, type, nature_name, yk_feature,name FROM yikao_college LEFT JOIN  yikao_college_c ON yikao_college.school_id = yikao_college_c.school_id  ORDER BY yikao_college.id");
        $colleges = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $total = count($colleges);
        foreach ($colleges as $college) {
            echo "Progress: {$college['name']}\n";
            $data = [];
            $tk_feature = json_decode($college['yk_feature'], true);
            if(in_array('八大美院', $tk_feature)) {
                $data[] = [
                    'college_id' => $college['school_id'] * 2 + 3,
                    'classify_id' => 1
                ];
            }
            if($college['f211'] == 1) {
                $data[] = [
                    'college_id' => $college['school_id'] * 2 + 3,
                    'classify_id' => 4
                ];
            }

            if($college['f985'] == 1) {
                $data[] = [
                    'college_id' => $college['school_id'] * 2 + 3,
                    'classify_id' => 2
                ];
            }

            if($college['type'] == 5009) {
                $data[] = [
                    'college_id' => $college['school_id'] * 2 + 3,
                    'classify_id' => 3
                ];
            }

            $data[] = [
                'college_id' => $college['school_id'] * 2 + 3,
                'classify_id' => $college['nature_name'] == '公办' ? 7 : 8
            ];

            if($data) {
                $insert = [];
                foreach ($data as $item) {
                    $insert[] = "({$item['college_id']}, {$item['classify_id']})";
                }
                $pdo->exec("INSERT INTO college_classify (college_id, classify_id) VALUES " . implode(',', $insert));
            }
            echo "Progress: {$college['name']}结束\n";
            $this->logMemoryUsage();
        }
    }

    protected function logMemoryUsage()
    {
        $memoryUsage = round(memory_get_usage(true) / (1024 * 1024), 2);
        $memoryLimit = ini_get('memory_limit');
        error_log("Memory usage: {$memoryUsage}MB of {$memoryLimit}");
    }

    protected function handleError(\Exception $e)
    {
        echo "\nERROR: " . $e->getMessage() . "\n";
        echo "File: " . $e->getFile() . " (Line: " . $e->getLine() . ")\n";

        error_log($e->getMessage() . "\nFile: " . $e->getFile() . " (Line: " . $e->getLine() . ")\n" . $e->getTraceAsString());

        exit(1);
    }
}

// 执行脚本
(new LogoDownloadScript())->run();
